package com.taomus.mytools.helper.properties;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.taomus.mytools.helper.stream.StreamHelper;

public class PropertiesHelper {

	private final static Logger logger = LoggerFactory.getLogger(PropertiesHelper.class);
	private Properties p = null;
	private static Map<String,Map<String,String>> phcache = new HashMap<String,Map<String,String>>();
	public static String get(String filename, String key) {
		if (filename != null) {
			InputStream input = null;
			if(phcache.containsKey(filename)){
				Map<String,String> ph = phcache.get(filename);
				if(ph.containsKey(key)) return ph.get(key);
				return null;
			}
			try {
				input = StreamHelper.getInputStreamByFileName(filename);
				if (input == null)
					return null;
				Properties p = new Properties();
				p.load(input);
				Set<Object> keys = p.keySet();
				Map<String,String> ph = null;
				if(phcache.containsKey(filename)){
					ph = phcache.get(filename);
				}else{
					ph = new HashMap<String,String>();
					phcache.put(filename,ph);
				}
				for(Object pk : keys){
					ph.put((String)pk,(String)p.get(pk));
				}
				if(ph.containsKey(key)) return ph.get(key);
				input.close();
				return null;
			} catch (IOException e) {
				logger.error("IOException", e);
				return null;
			}
		}
		return null;
	}

	public PropertiesHelper(String filename) {
		// ResourceBundle rb = ResourceBundle.getBundle(filename);
		p = new Properties();
		InputStream input = StreamHelper.getInputStreamByFileName(filename);
		try {
			p.load(input);
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally {
			try {
				input.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@SuppressWarnings("unchecked")
	public <T> T toJava(Class<T> cl) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		Object obj = cl.newInstance();
		Field[] fields = cl.getDeclaredFields();
		for (Field f : fields) {
			f.setAccessible(true);
			Propertie pro = f.getAnnotation(Propertie.class);
			String key = pro != null && !pro.value().equals("") ? pro.value().trim() : f.getName();
			if (p.containsKey(key)) {
				f.set(obj, p.get(key));
			}
		}
		return (T) obj;
	}
}
